package com.redsoft.epip.filter;

import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import com.redsoft.epip.config.BodyReaderHttpServletRequestWrapper;
import com.redsoft.epip.util.SensitiveWordUtil;
import com.redsoft.spirit.entity.JsonResult;


public class WordFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");

        //在过滤器中用装饰模式把 原装request的功能增强了
        //---拦截后台调用的getParamter()方法
        
        
        ServletRequest requestWrapper = null;  
        if(request instanceof HttpServletRequest) {  
            requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request);  
        }  
        if(null == requestWrapper) {  
            chain.doFilter(request, response);  
        } else {
            if("POST".equalsIgnoreCase(((HttpServletRequest) request).getMethod())){
//            	param = this.getBodyString(request.getReader());
            	String bodyString = this.getBodyString(requestWrapper.getReader());
            	
            	System.out.println("filter读取body中的参数>>>>>>>>>" + bodyString);
            	
            	if (SensitiveWordUtil.contains(bodyString)) {
            		response.getWriter().write(new JsonResult(null, "输入含有敏感词").failure().toString()); 
            		
            		return;
				}
            }
            
            chain.doFilter(requestWrapper, response);  
        }  
    }
    
    //获取request请求body中参数
  	public static String getBodyString(BufferedReader br) {
  		  String inputLine;
  		       String str = "";
  		     try {
  		       while ((inputLine = br.readLine()) != null) {
  		        str += inputLine;
  		       }
  		       br.close();
  		     } catch (IOException e) {
  		       System.out.println("IOException: " + e);
  		     }
  		     return str;
  		 }

    @Override
    public void destroy() {
    }
}